package com.naizhuai.ui.management;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.network.exception.ServerException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.adapter.ManageDividerItemDecoration;
import com.naizhuai.ui.adapter.management.StructureListAdapterHolder;
import com.naizhuai.ui.adapter.management.TeamMemberListAdapterHolder;
import com.naizhuai.ui.components.TipDialog;
import com.naizhuai.ui.entity.QRCodeMsgBean;
import com.naizhuai.ui.entity.QRCodeScanBean;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.ui.entity.management.DepartmentBean;
import com.naizhuai.ui.entity.management.ManagementMainMsgBean;
import com.naizhuai.ui.management.presenter.CompanyManageDataApiStore;
import com.naizhuai.ui.management.presenter.CompanyManageDataApiStoreIml;
import com.naizhuai.ui.mianbusiness.setting.ManageCreateQRCodeActivity;
import com.naizhuai.ui.mianbusiness.setting.ManageScanQRCodeActivity;
import com.naizhuai.ui.user.UserManageDataApiStoreIml;
import com.naizhuai.util.AddPersonUtils;
import com.naizhuai.util.CheckEntityByDialogUtils;
import com.naizhuai.util.ConstantsPersonResources;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.ListUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.RxUtils;
import com.naizhuai.util.SearchPersonByDialogUtils;
import com.naizhuai.util.SharedPreferenceUtil;
import com.naizhuai.util.ToastCompat;
import com.naizhuai.util.UidUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 组织的架构展示列表（人员列表+搜索）
 */
public class CompanyTeamStructureActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "CompanyTeamStructureActivity";
    private static final int OPERATE_DEPARTMENT_CODE = 1000;
    private static final int SCAN_ADD_PERSON_CODE = 1001;

    @BindView(R.id.department_name)
    TextView departName;
    @BindView(R.id.department_number)
    TextView departNumber;
    @BindView(R.id.department_member_list)
    RecyclerView departMemberList;
    private DepartmentBean department;
    @BindView(R.id.more_action_btn)
    ImageView editBtn;
    @BindView(R.id.scan_add_member)
    LinearLayout scanLayout;

    //组织成员
    private List<PersonUserBean> teamMember;
    private String departId;
    private TeamMemberListAdapterHolder adapter;
    private CompanyManageDataApiStore apiStore;
    private Observer<DepartmentBean> observer;
    private Subscription userinfoSub;

    //个人信息
    private PersonUserBean userInfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBaseData();
        initBaseView();
        initData();
    }

    public static void startActivity(Context mContext, String departmentId) {
        IntentUtils.startActivityWithString(DepartmentBean.DEPARTMENT_ID_KEY, departmentId, mContext, CompanyTeamStructureActivity.class);
    }

    private void initBaseData() {
        teamMember = new ArrayList<>();
    }

    private void initBaseView() {
        setManageRecyclerViewTest();
    }

    private void initData() {
        apiStore = CompanyManageDataApiStoreIml.getInstance();
        initBasicData();
    }

    private void initBasicData() {
        Bundle intentBundle = getIntent().getExtras();
        if (intentBundle != null) {
            departId = intentBundle.getString(DepartmentBean.DEPARTMENT_ID_KEY);
            initObserval();
        }
    }

    private void initObserval() {
        observer = new Observer<DepartmentBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                hideWaitDialog();
            }

            @Override
            public void onNext(DepartmentBean result) {
                hideWaitDialog();
                department = result;
                departName.setText(result.getDepartmentName());
                teamMember.clear();
                teamMember.addAll(result.getDepartmentMember());
                String numberFor = getString(R.string.no_one_number);
                departNumber.setText(String.format(numberFor, String.valueOf(teamMember.size())));
                adapter.notifyDataSetChanged();
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(departId)) {
            requestUserData();
            requestData();
        }
    }

    private void requestUserData() {
        if (!RxUtils.isNetRunning(userinfoSub))
            userinfoSub = UserManageDataApiStoreIml.getInstance().getuserinfo().subscribe(new Observer<PersonUserBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    if (e instanceof ApiException) {
                        ApiException ae = (ApiException) e;
                        DialogUtils.showPromptDialog(CompanyTeamStructureActivity.this, ae.getDisplayMessage());
                    }
                }

                @Override
                public void onNext(PersonUserBean personUserBean) {
                    userInfo = personUserBean;
                    String userDepartmentId = personUserBean.getDepartmentId();
                    String userDepartmentCode = personUserBean.getDepartmentPowerCode();
                    String userCompanyCode = personUserBean.getCompanyPowerCode();
                    if (!userCompanyCode.equals(ConstantsState.COM_NORMAL_POWER_LEVEL) || (userDepartmentId.equals(departId) && !userDepartmentCode.equals(ConstantsState.DEPARTMENT_NORMAL_POWER))) {
                        editBtn.setVisibility(View.VISIBLE);
                        scanLayout.setVisibility(View.VISIBLE);
                    } else {
                        editBtn.setVisibility(View.GONE);
                        scanLayout.setVisibility(View.GONE);
                    }

                }
            });
    }

    private void requestData() {
        String companyId = getShareValue(CompanyBean.COMPANY_ID_KEY, "");
        if (!TextUtils.isEmpty(companyId)) {
            Subscription requestSub = apiStore.getTeamDetailsByIds(companyId, departId).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
            showWaitDiaLog(requestSub);
        } else {
            DialogUtils.showPromptDialog(this, getString(R.string.no_company_error));
            finish();
        }
    }

    private void setManageRecyclerViewTest() {
        adapter = new TeamMemberListAdapterHolder(this, teamMember);
        departMemberList.setHasFixedSize(true);
        departMemberList.setNestedScrollingEnabled(false);
        departMemberList.setLayoutManager(new LinearLayoutManager(this));
        departMemberList.setItemAnimator(new DefaultItemAnimator());
        ManageDividerItemDecoration dividerDecoration = new ManageDividerItemDecoration(this, ManageDividerItemDecoration.VERTICAL_LIST, 5, true);
        dividerDecoration.setBaseFloat(0.3f);
        departMemberList.addItemDecoration(dividerDecoration);
        departMemberList.setAdapter(adapter);
        adapter.setOnItemClickListener(new TeamMemberListAdapterHolder.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                PersonUserBean userBean = teamMember.get(position);
                IntentUtils.startActivityWithString(PersonUserBean.USER_ID_KEY, userBean.getUid(), CompanyTeamStructureActivity.this, CompanyUserDetailsMsgActivity.class);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        switch (requestCode) {
            case OPERATE_DEPARTMENT_CODE:
                DepartmentBean departResultBean = (DepartmentBean) data.getSerializableExtra(DepartmentBean.DEPARTMENT_KEY);
                if (departResultBean == null)
                    return;
                switch (resultCode) {
                    case CompanyDepartmentOperatActivity.RESULT_SAVE:
                        departName.setText(departResultBean.getDepartmentName());
                        break;
                    case CompanyDepartmentOperatActivity.RESULT_DELETE:
                        finish();
                        break;
                }
                break;
            case SCAN_ADD_PERSON_CODE:
                QRCodeScanBean scanBean = (QRCodeScanBean) data.getSerializableExtra(QRCodeScanBean.SCAN_DATA_KEY);
                if (scanBean == null) {
                    DialogUtils.showPromptDialog(CompanyTeamStructureActivity.this, getString(R.string.qrcode_scan_error));
                    return;
                }
                if (!scanBean.getJoinType().equals(QRCodeMsgBean.USER_JOIN_TYPE) || TextUtils.isEmpty(scanBean.getUserId()))
                    DialogUtils.showPromptDialog(this, getString(R.string.only_person));
                else {
                    showWaitDiaLog();
                    NaizhuAILog.e("getUserId=" + (new UidUtil(scanBean.getUserId()).toString()));
                    NaizhuAILog.e("ADD_TYPE_TO_COMPANY=" + AddPersonUtils.ADD_TYPE_TO_COMPANY_DEPARTMENT);
                    NaizhuAILog.e("department=" + department.getDepartmentId());
                    NaizhuAILog.e("COM_NORMAL_POWER_LEVEL=" + ConstantsState.COM_NORMAL_POWER_LEVEL);
                    CompanyManageDataApiStoreIml.getInstance().insertPersonAddCompanyByIds(new UidUtil(scanBean.getUserId()).toString(),
                            AddPersonUtils.ADD_TYPE_TO_COMPANY_DEPARTMENT, department.getDepartmentId(),
                            ConstantsState.COM_NORMAL_POWER_LEVEL, null).subscribe(new Observer<String>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                            hideWaitDialog();
                            if (e instanceof ApiException) {
                                ApiException ae = (ApiException) e;
                                DialogUtils.showPromptDialog(CompanyTeamStructureActivity.this, ae.getDisplayMessage());
                            }
                        }

                        @Override
                        public void onNext(String s) {
                            hideWaitDialog();
                            if (ConstantsState.isResultOk(s)) {
                                DialogUtils.showPromptDialog(CompanyTeamStructureActivity.this, getString(R.string.user_add_ok));
                                requestData();
                            } else {
                                DialogUtils.showPromptDialog(CompanyTeamStructureActivity.this, getString(R.string.user_add_no));
                            }
                        }
                    });
                }
                break;
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_company_team_structure_layout;
    }


    @OnClick({R.id.back_icon, R.id.search_text, R.id.scan_add_member, R.id.more_action_btn})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_icon:
                super.onBackPressed();
                break;
            case R.id.search_text:
                IntentUtils.startActivity(this, CompanySearchActivity.class);
                break;
            case R.id.scan_add_member:
                if (department == null) {
                    shortToast(getString(R.string.depart_msg_error));
                    return;
                }
                IntentUtils.startActivityForResult(this, ManageScanQRCodeActivity.class, SCAN_ADD_PERSON_CODE);
                break;
            case R.id.more_action_btn:
                IntentUtils.startActivityWithObjectForResult(DepartmentBean.DEPARTMENT_KEY, department, this, CompanyDepartmentOperatActivity.class, OPERATE_DEPARTMENT_CODE);
                break;
        }
    }
}
